
//
//  ServiceLib.m
//  SOS
//
//  Created by Toan M. Ha on 2/4/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ServiceLib.h"

#import "Reachability.h"
#import "MHAppDelegate.h"
#import <CommonCrypto/CommonDigest.h>

#define kCacheDocument          @"Documents/Caches/"
#define kCacheFilePathFormat    @"%@%@",kCacheDocument

static ServiceLib* serviceLib;
static NSMutableDictionary*     mCache;
//static SDURLCache* mUrlCache;
@implementation ServiceLib{
    BOOL isOnline;
}

+(ServiceLib*)shareInstance {
	if (!serviceLib) {
		serviceLib = [[ServiceLib alloc] init];
	}
	return serviceLib;
}

+ (NSString*)sendSpecialGetRequest: (NSString*)strURL {
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]] ];
    //    [theRequest setCachePolicy:NSURLCacheStorageAllowed];
    
//    [theRequest setHTTPMethod:@"GET"];
    
    NSData* responeData;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSError* error;
    NSURLResponse* response;
    responeData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
    if (responeData==nil) {
        NSLog(@"error-- send get : %@", [error debugDescription]);
        return @"";
    }
    NSString *string = [[NSString alloc] initWithData:responeData encoding:NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    return string;
    
}

+ (NSString*)sendGetRequest:(NSString *)strURL useCache:(BOOL)isCached  {
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]] ];
    //    [theRequest setCachePolicy:NSURLCacheStorageAllowed];
    
    [theRequest setHTTPMethod:@"GET"];

    NSData* responeData;
    
    Reachability* reach = ((MHAppDelegate*)[UIApplication sharedApplication].delegate).reachability;
    NetworkStatus status = [reach currentReachabilityStatus];
    if (isCached && status == NotReachable) {
        NSString* data = [ServiceLib cacheForKey:strURL];
        if (data) {
            return data;
        }
        
    }
    else
    {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        NSError* error;
        NSURLResponse* response;
        responeData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
        if (responeData==nil) {
            NSLog(@"error-- send get : %@", [error debugDescription]);
            return @"";
        }
        NSString *string = [[NSString alloc] initWithData:responeData encoding:NSUTF8StringEncoding];
        [ServiceLib setCacheString:string forKey:strURL toDisk:YES];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        return string;
        
    }
    
    
    NSString *string = [[NSString alloc] initWithData:responeData encoding:NSUTF8StringEncoding];
    return string;
}

+(NSString*)sendGetRequest:(NSString*)strURL {
 
    return [self sendGetRequest:strURL useCache:YES];
}

+(NSString*)sendPostRequest:(NSMutableDictionary*)params andUrl:(NSString*)strURL {
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	[theRequest setHTTPMethod:@"POST"];
	
	NSString* paramStr = @"";
	
	if (params) {
		NSEnumerator *keys = [params keyEnumerator];
		
		for (int i = 0; i < [params count]; i++) {
			NSString *key = [keys nextObject];
			NSString *val = [params objectForKey:key];
			paramStr = [NSString stringWithFormat:@"%@&%@=%@",paramStr,key,val];
		}
	}
	
	if (paramStr.length > 0) {
		NSData* requestData = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
		NSString* requestDataLengthString = [NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]];
		[theRequest setHTTPBody: requestData];
		[theRequest setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];		
	}
	
	NSData* responeData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];	
	
	NSString *string = [[NSString alloc] initWithData:responeData encoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	return string;
	
}

+ (NSString*)cacheForKey:(NSString*)key {
    NSString* result;
    NSString* hashKey = [ServiceLib sha256:key];
    
    result = [ServiceLib readDataFromFile:hashKey];
    
    return result;
}

+ (void)setCacheString:(NSString*)string forKey:(NSString*)key toDisk:(BOOL)toDisk {
    NSString* hashKey = [ServiceLib sha256:key];

    if (toDisk) {
        [ServiceLib saveData:string toFile:hashKey];
    }
}


+ (NSString*)readDataFromFile:(NSString*)file {
    // get file path
    NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:kCacheFilePathFormat, file]];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSError* error;
        NSString* string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"read data from file error: %@", [error description]);
        }
        else {
        }
        
        return string;
    }
    return nil;
}

+ (void)saveData:(NSString*)data toFile:(NSString*)file {
    NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:kCacheDocument];
    if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // the file path
    NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:kCacheFilePathFormat, file]];
    
    NSError* error;
    [data writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"ServiceLib save data to file error! --> %@", [error description]);
    }
    else {
    }
}

+ (NSString*)sha256: (NSString*)input {
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(NSInteger i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}



@end
